/*
 * Copyright (C) 2014 Alpha, Inc.
 * This is NOT a freeware, use is subject to license terms.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.gehua.octopus.rpc.common.resource;

import cc.gehua.octopus.rpc.utils.IOUtil;
import cc.gehua.octopus.rpc.utils.URIUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author guna
 */

/* ------------------------------------------------------------ */
public class JarResource extends URLResource {

    private static final Logger LOG = LoggerFactory.getLogger(JarResource.class);
    protected JarURLConnection jarConnection;

    /* -------------------------------------------------------- */
    protected JarResource(URL url) {
        super(url, null);
    }

    /* ------------------------------------------------------------ */
    protected JarResource(URL url, boolean useCaches) {
        super(url, null, useCaches);
    }

    /* ------------------------------------------------------------ */
    @Override
    public synchronized void close() {
        jarConnection = null;
        super.close();
    }

    /* ------------------------------------------------------------ */
    @Override
    protected synchronized boolean checkConnection() {
        super.checkConnection();
        try {
            if (jarConnection != connection) {
                newConnection();
            }
        } catch (IOException e) {
            jarConnection = null;
        }

        return jarConnection != null;
    }

    /* ------------------------------------------------------------ */
    /**
     * @throws IOException Sub-classes of <code>JarResource</code> may throw an
     * IOException (or subclass)
     */
    protected void newConnection() throws IOException {
        jarConnection = (JarURLConnection) connection;
    }

    /* ------------------------------------------------------------ */
    /**
     * Returns true if the represented resource exists.
     *
     * @return
     */
    @Override
    public boolean exists() {
        if (urlString.endsWith("!/")) {
            return checkConnection();
        } else {
            return super.exists();
        }
    }

    /* ------------------------------------------------------------ */
    @Override
    public File getFile()
            throws IOException {
        return null;
    }

    /* ------------------------------------------------------------ */
    @Override
    public InputStream getInputStream()
            throws java.io.IOException {
        checkConnection();
        if (!urlString.endsWith("!/")) {
            return new FilterInputStream(getInputStream(false)) {
                @Override
                public void close() throws IOException {
                    this.in = IOUtil.getClosedStream();
                }
            };
        }

        URL url = new URL(urlString.substring(4, urlString.length() - 2));
        InputStream is = url.openStream();
        return is;
    }

    /* ------------------------------------------------------------ */
    @Override
    public void copyTo(File directory)
            throws IOException {
        if (!exists()) {
            return;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Extract " + this + " to " + directory);
        }

        String urlString = this.getURL().toExternalForm().trim();
        int endOfJarUrl = urlString.indexOf("!/");
        int startOfJarUrl = (endOfJarUrl >= 0 ? 4 : 0);

        if (endOfJarUrl < 0) {
            throw new IOException("Not a valid jar url: " + urlString);
        }

        URL jarFileURL = new URL(urlString.substring(startOfJarUrl, endOfJarUrl));
        String subEntryName = (endOfJarUrl + 2 < urlString.length() ? urlString.substring(endOfJarUrl + 2) : null);
        boolean subEntryIsDir = (subEntryName != null && subEntryName.endsWith("/"));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Extracting entry = " + subEntryName + " from jar " + jarFileURL);
        }

        try (InputStream is = jarFileURL.openConnection().getInputStream();
                JarInputStream jin = new JarInputStream(is)) {
            JarEntry entry;
            boolean shouldExtract;
            while ((entry = jin.getNextJarEntry()) != null) {
                String entryName = entry.getName();
                if ((subEntryName != null) && (entryName.startsWith(subEntryName))) {
                    // is the subentry really a dir?
                    if (!subEntryIsDir && subEntryName.length() + 1 == entryName.length() && entryName.endsWith("/")) {
                        subEntryIsDir = true;
                    }

                    //if there is a particular subEntry that we are looking for, only
                    //extract it.
                    if (subEntryIsDir) {
                        //if it is a subdirectory we are looking for, then we
                        //are looking to extract its contents into the target
                        //directory. Remove the name of the subdirectory so
                        //that we don't wind up creating it too.
                        entryName = entryName.substring(subEntryName.length());
                        shouldExtract = !entryName.equals("");
                    } else {
                        shouldExtract = true;
                    }
                } else shouldExtract = (subEntryName == null) || (entryName.startsWith(subEntryName));

                if (!shouldExtract) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Skipping entry: " + entryName);
                    }
                    continue;
                }

                String dotCheck = entryName.replace('\\', '/');
                dotCheck = URIUtil.canonicalPath(dotCheck);
                if (dotCheck == null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Invalid entry: " + entryName);
                    }
                    continue;
                }

                File file = new File(directory, entryName);

                if (entry.isDirectory()) {
                    // Make directory
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                } else {
                    // make directory (some jars don't list dirs)
                    File dir = new File(file.getParent());
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    // Make file
                    try (OutputStream fout = new FileOutputStream(file)) {
                        IOUtil.copy(jin, fout);
                    }

                    // touch the file.
                    if (entry.getTime() >= 0) {
                        file.setLastModified(entry.getTime());
                    }
                }
            }

            if ((subEntryName == null) || (subEntryName != null && subEntryName.equalsIgnoreCase("META-INF/MANIFEST.MF"))) {
                Manifest manifest = jin.getManifest();
                if (manifest != null) {
                    File metaInf = new File(directory, "META-INF");
                    metaInf.mkdir();
                    File f = new File(metaInf, "MANIFEST.MF");
                    try (OutputStream fout = new FileOutputStream(f)) {
                        manifest.write(fout);
                    }
                }
            }
        }
    }

    public static Resource newJarResource(Resource resource) throws IOException {
        if (resource instanceof JarResource) {
            return resource;
        }
        return Resource.newResource("jar:" + resource + "!/");
    }
}
